package com.yishusmt.mobsmt.serviceimpl;

import com.yishusmt.mobsmt.constant.CodeConstant;
import com.yishusmt.mobsmt.constant.UrlConstant;
import com.yishusmt.mobsmt.dto.base.Result;
import com.yishusmt.mobsmt.dto.request.EditPasswordReq;
import com.yishusmt.mobsmt.dto.request.UserLoginReq;
import com.yishusmt.mobsmt.dto.response.Tips;
import com.yishusmt.mobsmt.entity.UrlBodyEntity;
import com.yishusmt.mobsmt.entity.UserEntity;
import com.yishusmt.mobsmt.entity.UserLoginRecordEntity;
import com.yishusmt.mobsmt.enums.ResultCodeEnum;
import com.yishusmt.mobsmt.mapper.UserEntityMapper;
import com.yishusmt.mobsmt.mapper.UserInfoMapper;
import com.yishusmt.mobsmt.mapper.UserLoginRecordEntityMapper;
import com.yishusmt.mobsmt.service.LoginService;
import com.yishusmt.mobsmt.utils.DateUtil;
import com.yishusmt.mobsmt.utils.HttpClientUtil;
import com.yishusmt.mobsmt.utils.MD5Util;
import com.yishusmt.mobsmt.utils.TipsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yishusmt.mobsmt.enums.ResultCodeEnum.OPERATION_FAIL;
import static com.yishusmt.mobsmt.enums.ResultCodeEnum.OPERATION_SUCCESS;
import static com.yishusmt.mobsmt.enums.ResultCodeEnum.USER_LOGIN_SUCCESS;

/**
 * 用户登录
 *
 * @author zhangyi
 * @date 2018/8/9 15:34
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserEntityMapper userEntityMapper;

    @Autowired
    private HttpClientUtil httpClientUtil;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserLoginRecordEntityMapper userLoginRecordEntityMapper;


    /**
     * 用户登录
     *
     * @param userLoginReq
     * @return
     */
    @Override
    public Result login(UserLoginReq userLoginReq) {
        Result result = null;
        //密码加密
        String password = MD5Util.encryptString(userLoginReq.getPassword());
        userLoginReq.setPassword(password);
//     1手机端用户登录
//            与数据库中比较后
        UserEntity user = userInfoMapper.selectUser(userLoginReq);
        if(user != null ? true : false) {
//                1：成功：跳转首页
//                   （1）自动登录？存入手机本地 : 不存
            result = TipsUtil.returnTips(USER_LOGIN_SUCCESS,null);
        }else{
//                2：失败?使用远程用户登录
            result = loginRemote(userLoginReq);
        }
        if(result.getData() instanceof Tips) {
            Tips tips = (Tips) result.getData();
            if(tips.getCode().equals(USER_LOGIN_SUCCESS.key())){
                //获取当前的HttpServletRequest
                RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
                //创建用户登录实体
                UserLoginRecordEntity userLoginRecordEntity = new UserLoginRecordEntity();
                userLoginRecordEntity.setPhone(userLoginReq.getUsername());
                userLoginRecordEntity.setLoginIp(request.getRemoteAddr());
                userLoginRecordEntity.setLoginTime(DateUtil.getCurrentDate());
                userLoginRecordEntityMapper.insertSelective(userLoginRecordEntity);
            }
        }
        return result;
    }

    /**
     * 修改密码
     *
     * @param editPasswordReq
     * @return
     */
    @Override
    public Result editPassword(EditPasswordReq editPasswordReq) {
        //判断用户登陆
        UserLoginReq userLoginReq = new UserLoginReq(editPasswordReq.getPhone(),MD5Util.encryptString(editPasswordReq.getOldPassword()));
        UserEntity userEntity = userInfoMapper.selectUser(userLoginReq);
        if(userEntity != null) {
            String newPassword = MD5Util.encryptString(editPasswordReq.getNewPassword());
            userEntity.setPassword(newPassword);
            int i = userEntityMapper.updateByPrimaryKeySelective(userEntity);
            return 0 == i ? TipsUtil.returnTips(OPERATION_FAIL,null)
                    :TipsUtil.returnTips(OPERATION_SUCCESS,null);
        }else{
            return TipsUtil.returnTips(ResultCodeEnum.OPERATION_FAIL,null);
        }
    }

    /**
     * 远程用户登录
     *
     * @param userLoginReq
     */
    public Result loginRemote(UserLoginReq userLoginReq){
        String password = MD5Util.encryptString(userLoginReq.getPassword());
//      PC端用户数据登录
//      得到用户数据，存入手机端用户信息
        Map<String, Object> form = null;
        List<UrlBodyEntity> urlBodyList = new ArrayList<>();
        try {
            //远程角色赋值
            for (int i = 1; i < 3; i++) {
                //创建用户提交表单
                form = new HashMap();
                form.put("userName", userLoginReq.getUsername());
                form.put("type", i);
                form.put("password", userLoginReq.getPassword());
                urlBodyList.add(httpClientUtil.connectUrl(UrlConstant.memberLoginUrl, form));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Boolean[] userExist = new Boolean[]{false};
        urlBodyList.stream().forEach(urlBody ->
                userExist[0] = urlBody.getStatus().equals(CodeConstant.SUCCESS));
        if(userExist[0]){
//          (1):该用户存在 则存入手机端
            UserEntity userEntity = new UserEntity();
            //这里全都使用的手机号登入，原因嘛，你懂的
            userEntity.setPhone(userLoginReq.getUsername());
            userEntity.setPassword(password);
            userEntity.setCreateTime(DateUtil.getCurrentDate());
            userEntity.setUpdateTime(DateUtil.getCurrentDate());
            //将远程登录用户的信息存入本地
            int i = userEntityMapper.insertSelective(userEntity);
            return 0 == i ? TipsUtil.returnTips(ResultCodeEnum.OPERATION_FAIL,null):TipsUtil.returnTips(ResultCodeEnum.OPERATION_SUCCESS,null);
        }else{
//          (2):该用户不存在返回失败
            return TipsUtil.returnTips(ResultCodeEnum.OPERATION_FAIL,null);
        }
    }
}
